import { useLocation } from "react-router-dom";
import Layout from "../Shared/Layout";
import { Descriptions, message, Select, Tag, Input, Radio } from "antd";
import { requestDispatch } from "../../Api/api";
import React, { useState, useEffect, useCallback } from "react";
import { useDispatch } from "react-redux";
import MyButton from "../../Components/MyButton";
import { getUserTypeName } from "../../Api/name";
const UserDetail = () => {
  const location = useLocation();
  const urlParams = new URLSearchParams(location.search);
  const userId = urlParams.get("id");
  const [user, setUser] = useState({});
  const [departments, setDepartments] = useState([]);
  const [jobs, setJobs] = useState([]);
  const [isUpdating, setIsUpdating] = useState(false);
  const [updatingUser, setUpdatingUser] = useState({});
  const dispatch = useDispatch();
  const getJobListByDepartment = useCallback(
    async (depId) => {
      const res = await requestDispatch(
        dispatch,
        "/user/getJobListByDepartment",
        { depId: depId },
        "GET"
      );
      if (res.code >= 0) {
        setJobs(res.data);
      }
    },
    [dispatch]
  );
  useEffect(() => {
    async function fetchData() {
      // 获取单个用户信息
      const res = await requestDispatch(
        dispatch,
        "/user/one",
        { id: userId },
        "GET"
      );
      if (res.code >= 0) {
        setUser(res.data);
      }
      // 获取部门列表
      const res2 = await requestDispatch(
        dispatch,
        "/user/getDepList",
        {},
        "GET"
      );
      if (res2.code >= 0) {
        setDepartments(res2.data);
      }
      // 获取职位列表
      await getJobListByDepartment(res.data.depId);
    }
    fetchData();
  }, [dispatch, userId, getJobListByDepartment]);
  const toUpdating = () => {
    setUpdatingUser({ ...user });
    setIsUpdating(true);
  };
  const handleUpdate = async () => {
    let res = await requestDispatch(
      dispatch,
      "/user/update",
      { ...updatingUser },
      "POST"
    );
    if (res.code >= 0) {
      message.success(res.message);
      setUser({ ...res.data });
      setIsUpdating(false);
    } else {
      message.error(res.message);
    }
  };
  // >= 5.8.0 可用，推荐的写法 ✅

  const items = [
    {
      key: "1",
      label: "用户名",
      children: !isUpdating ? (
        <p>{user.name}</p>
      ) : (
        <Input
          value={updatingUser.name}
          onChange={(e) =>
            setUpdatingUser({ ...updatingUser, name: e.target.value })
          }
        />
      ),
    },
    {
      key: "2",
      label: "账号",
      children: !isUpdating ? (
        <p>{user.account}</p>
      ) : (
        <Input
          value={updatingUser.account}
          onChange={(e) =>
            setUpdatingUser({ ...updatingUser, account: e.target.value })
          }
        />
      ),
    },
    {
      key: "3",
      label: "电话",
      children: !isUpdating ? (
        <p>{user.phone == null ? "无" : user.phone}</p>
      ) : (
        <Input
          value={updatingUser.phone}
          onChange={(e) =>
            setUpdatingUser({ ...updatingUser, phone: e.target.value })
          }
        />
      ),
    },
    {
      key: "4",
      label: "部门",
      children: !isUpdating ? (
        <p>{user.depId == null ? "无" : user.depName}</p>
      ) : (
        <Select
          value={updatingUser.depId}
          style={{ display: "block" }}
          placeholder="请选择部门"
          onChange={(e) => {
            getJobListByDepartment(e);
            setUpdatingUser({ ...updatingUser, depId: e, jobId: "" });
          }}
        >
          <Select.Option value={""}>无</Select.Option>
          {departments.map((department) => (
            <Select.Option key={department.id} value={department.id}>
              {department.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      key: "5",
      label: "职位",
      children: !isUpdating ? (
        <p>{user.jobId == null ? "无" : user.jobName}</p>
      ) : (
        <Select
          value={updatingUser.jobId}
          placeholder="请选择职位"
          style={{ display: "block" }}
          onChange={(e) => setUpdatingUser({ ...updatingUser, jobId: e })}
        >
          <Select.Option value={""}>无</Select.Option>
          {jobs.map((job) => (
            <Select.Option key={job.id} value={job.id}>
              {job.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      key: "6",
      label: "用户类别",
      children: !isUpdating ? (
        <p>{getUserTypeName(user.type)}</p>
      ) : (
        <Select
          value={updatingUser.type}
          style={{ display: "block" }}
          onChange={(e) => setUpdatingUser({ ...updatingUser, type: e })}
        >
          {(() => {
            const options = [];
            for (let i = 1; i <= 4; i++) {
              options.push(
                <Select.Option key={i} value={i}>
                  {getUserTypeName(i)}
                </Select.Option>
              );
            }
            return options;
          })()}
        </Select>
      ),
    },
    {
      key: "7",
      label: "是否激活",
      children: (
        <p>
          {user.isActive === 1 ? (
            <Tag color="green">是</Tag>
          ) : (
            <Tag color="red">否</Tag>
          )}
        </p>
      ),
    },
    {
      key: "8",
      label: "是否禁用",
      children: !isUpdating ? (
        <p>
          {user.isBaned === 1 ? (
            <Tag color="red">是</Tag>
          ) : (
            <Tag color="green">否</Tag>
          )}
        </p>
      ) : (
        <Radio.Group
          block
          onChange={(e) => {
            setUpdatingUser({ ...updatingUser, isBaned: e.target.value });
          }}
          options={[
            {
              label: "是",
              value: 1,
              style: {
                backgroundColor: updatingUser.isBaned === 1 ? "#f50" : null,
              },
            },
            {
              label: "否",
              value: 0,
              style: {
                backgroundColor: updatingUser.isBaned === 0 ? "#87d068" : null,
              },
            },
          ]}
          defaultValue={updatingUser.isBaned}
          optionType="button"
          buttonStyle="solid"
        />
      ),
    },
    {
      key: "9",
      label: "创建时间",
      children: <p>{new Date(user.createTime).toLocaleString()}</p>,
    },
  ];

  return (
    <Layout>
      <Descriptions
        title="用户详情"
        layout="vertical"
        bordered
        items={items}
        extra={
          <div className="extra">
            {!isUpdating ? (
              <div className="extra-btn" onClick={toUpdating}>
                <MyButton type="warning">修改</MyButton>
              </div>
            ) : (
              <div className="extra-btn" onClick={handleUpdate}>
                <MyButton type="success">保存</MyButton>
              </div>
            )}
          </div>
        }
      />
    </Layout>
  );
};
export default UserDetail;
